var bigMap = null;
var allPhotos = [];
var rawPhotos = [];
var infoWindow = null;
var albums = [];
var geocoder;
var searchResults = [];
var filtered = [];
var latLngBoundsOriginal;
var searchBoxBig;
var markerClusterer;
var oms;
var allMarkers = [];
var overlay;
var tmax = 60;
var timeClusters = [];

function init_mainMap(){
	getAllPhotos();
	mountTimeClusters();
	chooseClusterLeaders();
}

function mountTimeClusters(){
	rawPhotos.sort(sortByDateFunction);
	var p_lastdate = null;
	var currentCluster = 0;
	timeClusters[currentCluster] = [];
	for(var photoIndex in rawPhotos){
		var photo = rawPhotos[photoIndex];
		var pDate = new Date(Date.parse(photo.date_taken));
		
		if(p_lastdate) alert(getTimeDif(p_lastdate, pDate));
		
		if(p_lastdate && getTimeDif(p_lastdate, pDate)>tmax){
			if(timeClusters[currentCluster].length>0){
				alert("ENTROU");
				currentCluster++;
				if(!timeClusters[currentCluster])
					timeClusters[currentCluster] = [];
			}
		}
		if((!photo.latitude || !photo.longitude)){
			photo["timeCluster"] = currentCluster;
			timeClusters[currentCluster].push(photo);
		}
		p_lastdate = pDate;
    }
}

function isTimeClustersEmpty(){
	var ret = true;
	if(timeClusters){
		for(var i in timeClusters){
			if(timeClusters[i]){
				ret = ret && timeClusters[i].length<=0;
			}
		}
	}
	return ret || !timeClusters;
}

function chooseClusterLeaders(){
	var innerHTMLPhotosNoLocation = "";
	if(!isTimeClustersEmpty()){
		document.getElementById("topoNoLocPhotos").style.height="100px";
		document.getElementById("gmap_photos").style.height="500px";
		innerHTMLPhotosNoLocation+='<h3 style="color: white; float: left; margin-left: 10px; vertical-align: middle;">Arraste as fotos para o local correto:</h3>';
		innerHTMLPhotosNoLocation+='<div style="width: 100%; height: 80%; float: left;">';
	}
	for(var timeCInd in timeClusters){
		var cluster = timeClusters[timeCInd];
		var pInd = Math.floor(cluster.length/2);
		var photo = cluster[pInd];
		innerHTMLPhotosNoLocation+= getPhotoNoLocationHTML(photo);
	}
	if(innerHTMLPhotosNoLocation.length>0){
		innerHTMLPhotosNoLocation+='</div>';
	}
	document.getElementById("topoNoLocPhotos").innerHTML = innerHTMLPhotosNoLocation;
}

function sortByDateFunction(photo1, photo2){
	var d = new Date(Date.parse(photo1.date_taken));
	var d2 = new Date(Date.parse(photo2.date_taken));
	
	return (d==d2?0:(d<d2?-1:1));
}

function getTimeDif(t1, t2){
	var dif = t1.getTime() - t2.getTime();
	var difSecs = dif/1000;
	
	return Math.abs(difSecs/60);
}

function getPhotoNoLocationHTML(photo){
	return '<a href="#" id="a'+photo["id"]+'"><img id="p'+photo["id"]+'" src="'+"./photos/"+photo["owner"]+"/thumbs/"+photo["file_name"]+'" draggable="true" ondragstart="drag(event)" style="margin-left:10px; float:left; max-height: 90%; max-width: 300px;"></a>';
}

function getAllPhotos(){
	$.ajax({
		url: "./map.php?"+getAlbumIdParameter+"="+currentAlbumId,
		type: "GET",
		dataType: "json",
		async: false,
		success: function(data) {
			if(data.status){
				//PROCESS data.photos
				geocoder = new google.maps.Geocoder();
				var latLngBoundsOriginal = new google.maps.LatLngBounds();
				if(data.albums){
					for(var albInd in data.albums){
						var album = data.albums[albInd];
						albums[album.id] = album;
					}
				}
				
				if(data.photos){
					for(var photoIndex in data.photos){
						var photo = data.photos[photoIndex];
						if(!allPhotos[photo.albumid])
							allPhotos[photo.albumid]= [];
						if(photo.latitude && photo.longitude){
							var point = new google.maps.LatLng(photo.latitude, photo.longitude);
							var imageUrl = "./photos/"+photo["owner"]+"/thumbs/"+photo["file_name"];
							var anchor = new google.maps.Point(25,25);
							var size = getImageScaledSize(photo.width, photo.height);
							var markerImage = {
								url: imageUrl,
								anchor: anchor,
								size: size,
								scaledSize: size
							};
							var markerLoc = new google.maps.Marker({
							    position: point,
							    bigMap: null,
							    icon: markerImage,
							});
							
							photo["marker"] = markerLoc;
							markerLoc["photo"] = photo;
							latLngBoundsOriginal.extend(point);
							
						}
						photo["label"] = albums[photo["albumid"]]["label"];
						allPhotos[photo.albumid].push(photo);
						rawPhotos.push(photo);
					}
				}
				init_bigMap(latLngBoundsOriginal);
			}else{
				init_bigMap();
				console.log(data.message);
			}
			
		},
		error: function(data) {
			console.log(data);
		}
	});
}

function editLocationMainMap(){
	editLocation();
	if(!photoMarker.draggable){
		var coord = photoMarker.getPosition();
		var photoid = document.getElementById("currentPhotoid").value;
		for(var ind in allMarkers){
			var mark = allMarkers[ind];
			if(mark["photo"].id==photoid){
				mark["photo"]["latitude"] = mark.getPosition().lat();
				mark["photo"]["longitude"] = mark.getPosition().lng();
				mark.setPosition(coord);
				bigMap.setCenter(coord);
			}
		}
	}
	
	markerClusterer.resetViewport();
	markerClusterer.redraw();
}

function getImageScaledSize(width, height){
	var iconDimensions = 100;
	if(width>height){
		/**new_width = iconDimensions;
		new_height = Math.round( height * ( iconDimensions / width ) );*/
		new_height = iconDimensions;
		new_width =  Math.floor( width * ( iconDimensions / height ) );
	}else{
		new_width = iconDimensions;
		new_height = Math.floor( height * ( iconDimensions / width ) );
	}
	
	return new google.maps.Size(new_width, new_height);
}
function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev){
	ev.dataTransfer.setData("photoid", ev.target.id);
}

function findPhotoById(pid){
	for(var albumIndex in allPhotos){
    	var album = allPhotos[albumIndex];
    	for(var photoIndex in album){
    		var photo = album[photoIndex];
    		if(photo["id"]==pid){
    			return photo;
    		}
    	}
    }
}

function handleDrop(e) {
	e.preventDefault();
//	var innerHTMLPhotosNoLocation = "";
	
	var divMap = document.getElementById("gmap_photos");
	
	var newP = new google.maps.Point((e.clientX-divMap.offsetLeft),(e.clientY-divMap.offsetTop));
	
	var coordinates = overlay.getProjection().fromContainerPixelToLatLng(newP);
	// process non-file (e.g. text or html) content being dropped
	// grab the plain text version of the data
	var pid = e.dataTransfer.getData('photoid');
	pid = pid.replace("p","");
	
	var newPhoto = findPhotoById(pid);
	var propagationIds = getTimeClusterIds(timeClusters[newPhoto["timeCluster"]]);
	var urlAdd = "./add_location.php?latitude="+coordinates.lat()+"&longitude="+coordinates.lng()+"&photoid="+pid+"&propagation="+propagationIds;
	alert(urlAdd);
	$.ajax({
		url: urlAdd,
		type: "GET",
		dataType: "json",
		async: false,
		success: function(data) {
			if(data.status){
				newPhotoMarker(pid, coordinates);
			}else{
				alert("Não foi possível referenciar a foto.");
			}
			
		},
		error: function(data) {
			console.log(data);
		}
	});
	
	return false;
}

function getTimeClusterIds(cluster){
	var ret="";
	var sep="";
	for(var i in cluster){
		ret+=sep+cluster[i].id;
		sep=",";
	}
	return ret;
}

function newPhotoMarker(pid, coordinates){
	var newPhoto = findPhotoById(pid);
	newPhoto["latitude"] = coordinates.lat();
	newPhoto["longitude"] = coordinates.lng();
	
	var clusterInd = newPhoto["timeCluster"];
	
	for(var photoInd in timeClusters[clusterInd]){
		var photo = timeClusters[clusterInd][photoInd];
		photo["timeCluster"] = null;
		photo["latitude"] = coordinates.lat();
		photo["longitude"] = coordinates.lng();
		addNewMarkerPhoto(photo,coordinates);
	}
	
	timeClusters[clusterInd] = [];
	var elemToRem = document.getElementById("a"+pid);
	elemToRem.parentNode.removeChild(elemToRem);
	if(isTimeClustersEmpty()){
		document.getElementById("topoNoLocPhotos").style.height="50px";
		document.getElementById("topoNoLocPhotos").innerHTML = "";
		document.getElementById("gmap_photos").style.height="550px";
	}
	markerClusterer.resetViewport();
	markerClusterer.redraw();
}

function addNewMarkerPhoto(newPhoto,coordinates){
	
	var imageUrl = "./photos/"+newPhoto["owner"]+"/thumbs/"+newPhoto["file_name"];
	var size = getImageScaledSize(newPhoto.width, newPhoto.height);
	var anchor = new google.maps.Point(Math.round(size.width/2),Math.round(size.height/2));
	
	var markerImage = {
		url: imageUrl,
		anchor: anchor,
		size: size,
		scaledSize: size
	};
	var markerLoc = new google.maps.Marker({
	    position: coordinates,
	    map: bigMap,
	    icon: markerImage,
	});
	
	google.maps.event.addListener(markerLoc, 'click', (function(innerPhoto) {
		return function(){
			$(".fundo").fadeIn();
			$(".overlap").center();
			$(".overlap").fadeIn();
			change(innerPhoto);
		};
	})(newPhoto));
	
	newPhoto["marker"] = markerLoc;
	markerLoc["photo"] = newPhoto;
	allMarkers.push(markerLoc);
	markerClusterer.addMarker(markerLoc);
}


function init_bigMap(latLngBounds) {
    var myOptions = {
        zoom: 1,
        maxZoom: 18,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        streetViewControl: false
    };
    bigMap = new google.maps.Map(document.getElementById("gmap_photos"), myOptions);
    if(latLngBounds)
    	bigMap.fitBounds(latLngBounds);
    
    overlay = new google.maps.OverlayView();
	overlay.draw = function() {};
	overlay.setMap(bigMap);
	
    var input = (document.getElementById('pac-input-big'));
    bigMap.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    searchBoxBig = new google.maps.places.SearchBox((input));
    
    google.maps.event.addListener(searchBoxBig, 'places_changed', function() {
    	searchResults = [];
		searchResults.push(-1);
		var results = searchBoxBig.getPlaces();
		
		filterSearch(results);
    });
    
    for(var albumIndex in allPhotos){
    	var album = allPhotos[albumIndex];
    	for(var photoIndex in album){
    		var photo = album[photoIndex];
    		if(photo["marker"]){
    			var markerLoc = photo["marker"];
    			markerLoc.setMap(bigMap);
    			allMarkers.push(markerLoc);
    			google.maps.event.addListener(markerLoc, 'click', (function(innerPhoto) {
    				return function(){
    					$(".fundo").fadeIn();
    					$(".overlap").center();
    					$(".overlap").fadeIn();
    					change(innerPhoto);
	    			};
	    		})(photo));
    		}
    	}
    }
    
    markerClusterer = new MarkerClusterer(bigMap, allMarkers, {
    	gridSize: 70,
    	zoomOnClick: false
    });

    google.maps.event.addListener(markerClusterer, 'clusterclick', function(cluster) {
    	if(bigMap.getZoom()<18){
    		bigMap.fitBounds(cluster.getBounds());
    	}else{
    		var info = new google.maps.MVCObject;
            info.set('position', cluster.getCenter());
            if(!infoWindow){
            	infoWindow = new google.maps.InfoWindow();
            }
            
            infoWindow.close();
            var clusterMarkersLocal = cluster.getMarkers();
            var contentLoc = "";
            for(var markLocInd in clusterMarkersLocal){
            	var markLoc = clusterMarkersLocal[markLocInd];
            	var photoLoc = markLoc["photo"];
            	var photoContent = '<li draggable="false" style="display: inline-block;">';
            	photoContent+='<a draggable="false" onclick="verFotoRef('+photoLoc["id"]+')" href="#" style="float:left;"><img draggable="false" style="max-height: 90%; float: left; margin-left: 10px;" src="./photos/'+photoLoc["owner"]+'/thumbs/'+photoLoc["file_name"]+'"/></a>';
            	photoContent+="</li>";
            	contentLoc+=photoContent;
            	
            }
            var infoContent = '<div draggable="false" style="max-height: 150px; max-width:410px; min-width: 100px; overflow: auto; white-space:nowrap; display:inline-block;">'+contentLoc+'</div>';
            infoWindow.setContent(infoContent);
            infoWindow.open(bigMap, info);
    	}
    	
    	return false;
    });
}

function filterSearch(results){
	if(results && results.length>0){
		var latLngBounds = results[0].geometry.bounds;
		if(!latLngBounds) latLngBounds = results[0].geometry.viewport;
		if(latLngBounds){
			filterPhotos();
			bigMap.fitBounds(latLngBounds);
		}else{
			bigMap.setCenter(results[0].geometry.location);
			bigMap.setZoom(15);
		}
	}else{
		bigMap.setCenter(new google.maps.LatLng(0,0));
		bigMap.setZoom(1);
	}
}

function searchMap(){
	var searchString = document.getElementById("buscaMapaId").value;
	if(searchString && searchString.length>0){

		geocoder.geocode( { 'address': searchString}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				searchResults = [];
				searchResults.push(-1);
				filterSearch(results);
			}
		});
	}else{
		searchResults = [];
		filterPhotos();
	}
}

function filterPhotos(){
	var filterAndSearch = filtered.concat(searchResults);
	var latLngBounds = new google.maps.LatLngBounds();
	for(var aI in allPhotos){
		var alb = allPhotos[aI];
		for(var pI in alb){
			var p = alb[pI];
			var markerLoc = p["marker"];
			if(markerLoc){
				var pid = ""+p["id"];
				if(filterAndSearch.length>0 && filterAndSearch.indexOf(pid)<0){
					markerLoc.setMap(null);
				}else{
					latLngBounds.extend(markerLoc.getPosition());
					markerLoc.setMap(bigMap);
				}
			}
		}
	}
	bigMap.fitBounds(latLngBounds);
}

google.maps.event.addDomListener(window, 'load', init_mainMap);